import re
from flask import Flask,request,jsonify
from flask_cors.core import ensure_iterable
# 实现orm，对象关系映射
from flask_sqlalchemy import SQLAlchemy
import sqlalchemy
from config import Config
from flask_cors import CORS
import json
import os

app = Flask(__name__)
db = SQLAlchemy(app)
CORS(app)
app.config.from_object(Config)
# 创建分类表
class Cate(db.Model):
    __tablename__='cate'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(20),unique=True)
    level = db.Column(db.Integer,default=1)
    pid = db.Column(db.Integer,default=0)

class Course(db.Model):
    __tablename__='course'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(50),unique=True)#名称唯一
    description = db.Column(db.Text,default='')#描述
    tname = db.Column(db.String(50),default='')#讲师
    pic = db.Column(db.String(255),default='')#图片
    vedios = db.Column(db.String(255),default='')#视频['','']
    status = db.Column(db.Integer,default=1)#审核状态
    reason=db.Column(db.String(255),default='')#失败原因
    cid =  db.Column(db.Integer,db.ForeignKey('cate.id'))#所属分类
# db.create_all()

@app.route('/cateM',methods = ['POST','GET','DELETE'])
def cateM():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        try:
           id  = data['id']
        except:
            id = 0
        if id:
            Cate.query.filter_by(id=id).update({'name':data['name']})
            db.session.commit()
        else:    
            cate = Cate(name = data['name'])
            db.session.add(cate)
            db.session.commit()
        return jsonify({'code':200})

    elif request.method=='GET':
      
        page = int(request.args.get('page'))
        # 每页显示3条
        page_size = 3
        start = (page-1)*page_size
        cates =Cate.query.offset(start).limit(page_size)
        list =[]
        for i in cates:
            dict = {'id':i.id,'name':i.name}
            list.append(dict)
        total = Cate.query.count()
        
        return jsonify({'code':200,'list':list,'total':total})

    elif request.method=='DELETE':
        id = request.args.get('id')
        Cate.query.filter_by(id=id).delete()
        db.session.commit()
        return jsonify({"code":200})

    
@app.route('/getcateByid')
def getcateByid():
    id = request.args.get('id')
    cate = Cate.query.filter_by(id=id).first()
    dict = {'id':cate.id,'name':cate.name}
    return jsonify({'code':200,'cate':dict})

@app.route('/upload',methods=['POST','GET'])
def upload():
    if request.method=='POST':
        file = request.files['file']
        file.save(os.path.join('./static/upload/',file.filename))
        # 如果有id更新数据库
        try:
            id = request.form['id']
            # 获取type
            type = request.form['type']
            print(type)
            if type == 1:
                Course.query.filter_by(id=id).update({'pic':file.filename})
                db.session.commit()
            else:
                # 更新视频
                course = Course.query.filter_by(id=id).first()
                # 获取视频列表转换成列表
                if course.vedios:
                    clist = json.loads(course.vedios)
                    videoname = request.form['videoname']
                    # 把列表中的视频文件替换
                    clist = [file.filename if i==videoname else i for i in clist]
                    if len(clist)>0:
                         vedios=json.dumps(clist,ensure_ascii=False)
                    else:
                        vedios=''
                #更新数据库vedios
                Course.query.filter_by(id=id).update({'vedios':vedios})
                db.session.commit()
        except:
            pass
        return jsonify({"code":200,'pic':file.filename})



    elif request.method=='GET':
        cates = Cate.query.all()
        list=[]
        for i in cates:
            dict = {'id':i.id,'name':i.name}
            list.append(dict)
        return jsonify({'code':200,'list':list})


@app.route('/courseM',methods=['POST','GET'])
def courseM():
    if request.method == 'POST':
        #接收客户传递的参数
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        #构造数据
        #判断是添加还是修改
        # try:
            pass
            #  id = data['id']
            #  #修改
            #  Course.query.filter_by(id=id).update({'name':data['name'],'description':data['description'],'tname':data['tname'],'cid':data['cid']})
        # except:
        course = Course(name=data['name'],description=data['description'],tname=data['tname'],pic=data['pic'],vedios=data['vedios'],cid=data['cid'])
            #添加
        db.session.add(course)
        #提交
        db.session.commit()
        #返回
        return jsonify({'code':200})

    elif request.method == "GET":
        #获取参数
        #当前点击的页面，如果没点击默认为1
        page = int(request.args.get('page'))
        #每页显示多少条
        size = int(request.args.get('size'))
        #读取数据
        start = (page-1)*size
        course = Course.query.offset(start).limit(size)
        #对结果解析
        list=[]
        if course:
            for i in course:
                list.append({'id':i.id,'name':i.name,'pic':i.pic,'tname':i.tname})
        #获取共有多少条记录
        total = Course.query.count()
        #返回
        return jsonify({"code":200,'list':list,'total':total})


@app.route('/courss')
def courss():
    id = request.args.get('id')
    course = Course.query.filter_by(id=id).first()
    cour = {'id':course.id,'name':course.name,'description':course.description,'tname':course.tname,'pic':course.pic,'vedios':course.vedios,'cid':course.cid}
    return jsonify({'code':200,'course':cour})

@app.route('/delFile',methods=['DELETE'])
def delFile():
    name = request.args.get('name')
    if not name:
        return jsonify({'code':10010,'mes':'必须传递要删除的图片'})
    # 从服务器上直接删除图片
    os.remove('./static/upload/'+name)
    # 更新数据
    id = request.args.get('id')
    type = request.args.get('type')
    if type == 1:
        Course.query.filter_by(id=id).update({'pic':''})
        db.session.commit()
    else:
        
             #视频列表
         course = Course.query.filter_by(id=id).first()
         #获取视频列表转成列表
         if course.vedios:
            clist = json.loads(course.vedios)
            #从列表中移除当前视频
            clist.remove(name)
            if len(clist) >0:
                vedios=json.dumps(clist,ensure_ascii=False)
            else:
                vedios=''
            #更新数据库vedios
            Course.query.filter_by(id=id).update({'vedios':vedios})
            db.session.commit()
    return jsonify({'code':200})

if __name__ == '__main__':
    app.run(debug=True)
    